import processing.core.*;
import processing.serial.*;
import java.io.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;



public class MyProcessingSketch extends PApplet {

	private Serial myPort;  // The serial port
	private int lf = 10;    // Linefeed in ASCII
	private int star = 42;    // Asteriks in ASCII
	private int[] AllReadValues = new int[1300];
	private int lastValueRead = 0;

	private boolean PortSelected = false;

	public static String now(String dateFormat) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		return sdf.format(cal.getTime());

	}

	public void setup() {
		size(1300,400);
		background(255);

		fill(0);
		// List all the available serial ports:
		String[] SerialPorts = Serial.list();
		text("Press number key (0..9) to select serial port",10,20);
		for(int i = 0;i < SerialPorts.length;i++){
			text("["+i+"] "+SerialPorts[i],300,40+20*i);
		}
		//while(!PortSelected){}

	}

	public void draw() {
		if(!PortSelected){

		}
		if(PortSelected){
			stroke(0);
			while (myPort.available() > 0) {
				String inBuffer = myPort.readStringUntil(star);  
				if (inBuffer != null) {
					inBuffer = inBuffer.substring(0, inBuffer.length()-1);
					int valueRead = Integer.parseInt(inBuffer);
					String valueReadString = String.valueOf(valueRead);
					long timestamp = System.currentTimeMillis();
					String timestampS = now("dd/MM/yyyy HH:mm:ss");
					
					AllReadValues[1299] = valueRead;
					// Shift left
					System.arraycopy(AllReadValues, 1, AllReadValues, 0, AllReadValues.length - 1);
					background(255);
					DrawGraph();

					fill(0);

					// we only save if we have a change
					if(lastValueRead != valueRead)
					{
						try {
							BufferedWriter out = new BufferedWriter(new FileWriter("poweruse.csv", true));
							out.write("\""+timestampS + "\", " + valueReadString + "\r\n");
							out.close();
						} catch (IOException e) {
							println("IOException: " + e.getMessage());
						}
						
						save("graph.png");
						lastValueRead = valueRead;
					}
				}				
			}
		}
	}

	public void DrawGraph(){
		fill(0);
		stroke(0);
		// Loop through and find min and max
		int minRV = 2147483647; int maxRV = 0;
		for(int i=0;i<AllReadValues.length;i++){
			maxRV = max(maxRV,AllReadValues[i]);
			minRV = min(minRV,AllReadValues[i]);
		}		
		// Never under 500
		maxRV = max(maxRV,500);
		
		for(int i=0;i<AllReadValues.length-1;i++){
			int v1 = AllReadValues[i];
			int v2 = AllReadValues[i+1];
			v1 = (int) map(v1,0,maxRV,0,height);
			v2 = (int) map(v2,0,maxRV,0,height);
			line(i,height-v1,i+1,height-v2);
		}
		int vi = (int) map(AllReadValues[1299],0,maxRV,0,height);
		fill(204, 102, 0);
		text(""+AllReadValues[1299],width-25,height-vi+10);
		
		DrawGridLines(maxRV);

	}
	public void DrawGridLines(int maxRV){
		int i = 0;
		fill(204, 102, 0);
		stroke(204, 102, 0);
		while(i < maxRV){
			int vi = (int) map(i,0,maxRV,0,height);
			line(0,height-vi,width,height-vi);
			text(i,10,height-vi-1);
			i = i + 250;
		}
	}
	public void keyPressed() {
		// Are we in state for selecting Serial POrt? 
		if(!PortSelected){
			int keyIndex = -1;
			if (key >= '0' && key <= '9') {
				keyIndex = key - '1'+1;
			}
			try {
				//println(keyIndex);
				myPort = new Serial(this, Serial.list()[keyIndex], 9600);
				PortSelected = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}	
		}
	}
}